package com.shenyue.nbtownlet.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 颖杰_2 on 2017-06-20.
 */

public class FileUtil {

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot);
            }
        }
        return filename;
    }

    public static List<byte[]> toByte(File file) {
        int byte_length = 1024 * 1024;
        List<byte[]> list = new ArrayList<>();
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            int diff = (int) Math.ceil((double) buffer.length / byte_length);
            if (diff == 1) {
                list.add(buffer);
                return list;
            }
            for (int i = 0; i < diff - 1; i++) {
                byte[] data = new byte[byte_length];
                System.arraycopy(buffer, i * byte_length, data, 0, data.length);
                list.add(data);
            }
            int $diff = buffer.length - (diff - 1) * byte_length;
            byte[] data = new byte[$diff];
            System.arraycopy(buffer, (diff - 1) * byte_length, data, 0, data.length);
            list.add(data);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputFile != null) {
                try {
                    inputFile.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
